import httplib
import json
import time
from com.kjssoft.eagleye import LOGGER
from com.kjssoft.eagleye.social.models import SocialUser, Auth
from com.kjssoft.eagleye.social.platform import SocialBindClientServer

__author__ = 'KJS'


class BindClientServer(SocialBindClientServer):
    AUTHORIZE_CODE_URL = 'https://graph.renren.com/oauth/authorize' \
                        '?client_id=%s&response_type=code&' \
                        'redirect_uri=http://%s/eagleye/social/connect/?bind=%s&display=page'
    AUTH_TOKEN_URL = '/oauth/token?grant_type=authorization_code&client_id=%s' \
                     '&redirect_uri=%s&client_secret=%s&code=%s'

    def __init__(self, bind, code = None):
        super(BindClientServer, self).__init__(bind)
        self.code = code

    def get_social_auth_url(self, host = None):
        return self.AUTHORIZE_CODE_URL % (
            self.bind.app_id,
            host,
            self.bind.id
        )

    def get_social_user_auth(self, host=None):
        connection = httplib.HTTPSConnection('graph.renren.com')
        url = self.AUTH_TOKEN_URL % (
            self.bind.app_id,
            'http://%s/eagleye/social/connect/?bind=%s' % (host, self.bind.id),
            self.bind.app_secret,
            self.code
        )
        connection.request("GET", url)
        response = connection.getresponse()
        data = json.loads(response.read())
        user = data['user']
        LOGGER.debug('renren user %s' % user)
        snapshot = user['avatar']
        if snapshot:
            for s in snapshot:
                LOGGER.debug(str(s['type']))
                if str(s['type']) == 'large':
                    snapshot = str(s['url'])
                    break
        if not snapshot or len(snapshot) == 0 or not isinstance(snapshot, str):
            snapshot = ''
        LOGGER.debug('renren user %s snapshot %s' % (
            user['name'],
            snapshot
        ))
        social_user = self.get_social_user(
            user['id'],
            self.bind.platform,
            name = user['name'],
            nickname = user['name'],
            snapshot = snapshot
        )
        auth = self.get_auth(
            social_user,
            self.bind,
            refresh_token = data['refresh_token'],
            access_token = data['access_token'],
            expire = int(data['expires_in'])
        )
        connection.close()
        return auth

    def get_social_user(self, social_user_uuid, platform, name=None, nickname=None, snapshot=None):
        social_users = SocialUser.objects.filter(
            social_uuid = social_user_uuid,
            platform = platform
        )
        if social_users.count():
            social_user = social_users[0]
        else:
            social_user = SocialUser.objects.create(
                social_uuid = social_user_uuid,
                platform = platform,
                name = name,
                nickname = nickname,
                snapshot = snapshot
            )
        social_user.name = name
        social_user.snapshot = snapshot
        LOGGER.debug('%s snapshot %s.' % (social_user, snapshot))
        social_user.save()
        return social_user

    def get_auth(self, social_user, bind, refresh_token=None, access_token=None, expire=0):
        auths = Auth.objects.filter(
            social_user = social_user,
            bind = bind
        )
        if auths.count():
            auth = auths[0]
        else:
            auth = Auth.objects.create(
                social_user = social_user,
                bind = bind,
                auth_ms = int(time.time())
            )
        auth.refresh_token = refresh_token
        auth.access_token = access_token
        auth.expire_in = expire
        auth.save()
        return auth

